package mysql

import (
	"errors"
	"gorm.io/gorm"
	"hzer/pkg/util"
)

type UserCode struct {
	gorm.Model
	Code         string `gorm:"type:varchar(255);not null;unique"`  // 授权码
	Used         bool   `gorm:"type:tinyint(1);not null;default:0"` // 是否使用
	Binds        string `gorm:"type:text;not null"`                 // 绑定信息,json格式
	MaxBind      int    `gorm:"type:int(11);not null;default:1"`    // 最大绑定数
	MaturityTime int64  `gorm:"type:bigint;not null;default:0"`     // 到期时间

	db *gorm.DB `gorm:"-"`
}

func NewUserCodeInstance() *UserCode {
	return &UserCode{
		db: GetDB().Model(&UserCode{}),
	}
}

func (t *UserCode) AddUserCode(MaxBind int, MaturityTime int64) (string, error) {
	code := util.RandomStr(64)
	err := t.db.Create(&UserCode{
		Code:         code,
		Used:         false,
		Binds:        "[]",
		MaxBind:      MaxBind,
		MaturityTime: MaturityTime,
	}).Error
	return code, err
}

func (t *UserCode) GetUserCodeByCode(code string) (*UserCode, error) {
	err := t.db.First(&t, "code = ?", code).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	return t, err
}
